(function(){
	
	if (!window.CJ) {
		window.CJ = {};
	}

	
	//Search Btn 
	function Search () {
		this.name = 'Search';
		this.bindEvent();
	}
	
	Search.prototype = new EventCtl();
	Search.prototype.bindEvent = function () {
		$('#global .search').on('click', function() {
			CJ.Scene.searchDetail();
		});
		$('#global .search').on('mouseenter', function() {
			if(!CJ.isRightDetailEntry) {
			$('#global li').removeClass('focus');
			$('#global .search').addClass('focus');
			CJ.Scene.setDelegate(CJ.Scene["Search"]);
			}
		});
	};
	Search.prototype.down = function () {
		CJ.Scene.banner();
	};
	Search.prototype.left = function () {
		CJ.Scene.myinfo();
	};
	Search.prototype.right = function () {
		CJ.Scene.promotion();
	};
	Search.prototype.back = function () {
		$("#wrap").removeClass('search');
		$('#global li').removeClass('focus');
		CJ.Scene.channel();
	};
	Search.prototype.enter = function () {
		CJ.Scene.searchDetail();
	};
	
	
	//Search 
	function SearchDetail () {
		this.name = 'SearchDetail';
		this.rootID = '#search';
		this.rootElem = $(this.rootID + " .searchBtn");
		this.bindEvent();
	}
	
	SearchDetail.prototype = new EventCtl();
	SearchDetail.prototype.bindEvent = function () {
		var self = this;
		$('#searchInput').on('focus', function(evt){
			$('#search .searchBtn .focus').removeClass('focus');
		});
		$('#voiceBtn').on('click', function(evt){
			$('#search .result .focus').removeClass('focus');
			self.enter();
		});
		$('#search .submit').on('click', function() {
			$('#search .result .focus').removeClass('focus');
			self.enter();
		});
		$('#search .cancel').on('click', function() {
			$('#search .result .focus').removeClass('focus');
			self.back();
		});
		$(this.rootElem).on('mouseenter', 'li', function() {
			if (!CJ.isLgKeyboardShow) {
				$(this).addClass('focus').siblings().removeClass('focus');
				$('#search .result .focus').removeClass('focus');
				CJ.Scene.setDelegate(CJ.Scene["SearchDetail"]);
			}
		});
	};
	SearchDetail.prototype.up = function () {
		this.back();
	};
	SearchDetail.prototype.down = function () {
		CJ.Scene.searchResult();
	};
	SearchDetail.prototype.left = function () {
		this.moveH('prev');
	};
	SearchDetail.prototype.right = function () {
		this.moveH('next');
	};
	SearchDetail.prototype.moveH = function (func) {
		var idx, now = $('li.focus', this.rootElem),
			next = now[func]();
		if (now.length == 0) {
			var s = $('#search .submit');
			s.addClass('focus');
			s.focus();
		} else {
			if (next.length>0) {
				now.removeClass('focus');
				next.addClass('focus');
			} else {
				if (func == 'prev') {
					now.removeClass('focus');
					$('#searchInput').focus();
					
					//LG 키패드를 매직마우스로 없애면 다음번 포커스가 제대로 동작하지만
					//4방향 키로 오른쪽 맨하단 키보드 감추기 버튼을 누른 경우 다음 번부터는 input에 포커스가 들어가도
					//LG 키패드가 나오지 않음 
					//강제로 키패드가 나오도록 호출
					CJ.util.lgKbForceShow($('#searchInput')[0]);
				}
			}
		}
	};
	SearchDetail.prototype.back = function () {
		CJ.Scene.search();
	};
	SearchDetail.prototype.enter = function () {
		var now = $('li.focus', this.rootElem);
		var searchKeyWord;
		if (now.hasClass('submit')) {
			searchKeyWord = $('#searchInput').val();
			if (searchKeyWord != '') {
				SearchResult.search(searchKeyWord);
			} else {
				$("#search .result").hide();
				return;
			}
		} else if (now.hasClass('cancel')) {
			$('#searchInput').val('');
			this.back();
		} else if (now.hasClass('symbol')) {
			CJ.plugin.voice.startRecognition();
		} else {
			//LG Keyboard 닫는 버튼을 누르면 바로 enter 이벤트가 전달됨 submit, cancel에 포커스가 있을 경우 해당 동작이 발생됨
			//하단에 setTimeout으로 포커스를 늦게 주도록 설정
			console.log('keyboard disappear');
			lgKb.focusOut();
		}
	};
	SearchDetail.prototype.enterInputField = function () {
		lgKb.focusOut();
		$('#search .submit').addClass('focus');
		this.enter();
	};
	
	
	//Search Result
	function SearchResult () {
		this.name = 'SearchResult';
		this.rootID = '#search .result';
		this.rootElem = $("#searchResultList");
		this.bindEvent();
	}
	
	SearchResult.searchKeyWord = null;
	SearchResult.lists = [];
	SearchResult.totalCount = 0;
	SearchResult.pageSize = 50;
	SearchResult.pageNo = 0;
	SearchResult.init = function () {
		this.searchKeyWord = null;
		this.lists = [];
		this.totalCount = 0;
		this.pageNo = 0;
		$('#search .result').hide();
	};
	SearchResult.search = function (searchKeyWord) {
		SearchResult.init();
		SearchResult.getData(searchKeyWord);
	};
	SearchResult.getData = function (searchKeyWord) {
		CJ.HttpJson.get({
			type: 'SEARCH',
			param: {
				searchText: searchKeyWord,
				pageSize: this.pageSize,
				pageNo: this.pageNo+1
			},
			success: function (json) {
				SearchResult.searchKeyWord = searchKeyWord;
				SearchResult.successCB(json);
			}
		});
	};
	SearchResult.successCB = function (json) {
		if (json.resultcode == 300) {
			$("#search .result").hide();
			CJ.Scene.alert("\""+$('#search .input').val()+"\" 검색결과가 없습니다", function () {CJ.Scene.searchDetail(); });
			return;
		}

		this.lists  = this.lists.concat(json.episodelist);
		this.totalCount = parseInt(json.total_count);
		this.totalPage =  parseInt(json.page_info.total_page);
		this.pageNo =  parseInt(json.page_info.page);
		//데어트를 추가로 로드할 경우 데이터만 추가 되고, 화면 처리는 않함.
		if (json.page_info.page == 1) {
			CJ.Scene["SearchResult"].render();
			$('#search .result').show();
		}
	};
	SearchResult.getMore = function () {
		if (this.totalPage != this.pageNo) {
			this.getData(SearchResult.searchKeyWord);
		}
	};
	SearchResult.prototype = new EventCtl();
	SearchResult.prototype.bindEvent = function () {
		var self = this;
		$(this.rootID + ' .btn_prev').on('click', function() {
			self.enter();
		});
		$(this.rootID + ' .btn_next').on('click', function() {
			self.enter();
		});
		$(this.rootElem).on('click', 'li', function() {
			self.enter();
		});
		
		$(this.rootID + ' .btn').on('mouseenter', function() {
			$('#search .searchBtn .focus').removeClass('focus');
			$('#searchResultList .focus').removeClass('focus');
			$(self.rootID + ' .btn.focus').removeClass('focus');
			$(this).addClass('focus');
			CJ.Scene.setDelegate(CJ.Scene["SearchResult"]);
		});
		$(this.rootElem).on('mouseenter', 'li', function() {
			$('#search .searchBtn .focus').removeClass('focus');
			$('#searchResultList .focus').removeClass('focus');
			$(self.rootID + ' .btn.focus').removeClass('focus');
			$(this).addClass('focus');
			CJ.Scene.setDelegate(CJ.Scene["SearchResult"]);
		});
	};
	SearchResult.prototype.render = function (sIdx) {
		sIdx = sIdx || 0;
		var len = SearchResult.lists.length;
		var range = 4;
		var arr = [];
		if (len < (range+sIdx) ){
			range = len - sIdx;
		}
		
		for (var i=0; i<range; i++) {
			arr.push(SearchResult.lists[i+sIdx]);
		}
		this.sIdx = sIdx ;
		
		$( this.rootElem ).html(
			$.render.myPlayListTemplate( arr )
		);
		this.pageNum(sIdx);
	};
	
	SearchResult.prototype.pageNum = function(idx) {
		var total = SearchResult.totalCount;
		$(this.rootID+' .btn>span').text(parseInt(idx+1)+'/'+total);
	};
	SearchResult.prototype.extend = function() {
		SearchResult.getMore();
	};
	SearchResult.prototype.left = function () {
		this.moveH('prev');
	};
	SearchResult.prototype.right = function () {
		this.moveH('next');
	};
	SearchResult.prototype.moveH = function (downup) {
		this.extend();
		var now = $("li.focus", this.rootElem);
		var btn = $(this.rootID + " .btn.focus");
		var next = now[downup]();
		if (now.length>0) {
			if (next.length>0) {
				$("li", this.rootElem).removeClass('focus');
				next.addClass('focus');
			} else {
				$("li", this.rootElem).removeClass('focus');
				$(this.rootID + ' ' + (downup == 'next' ? '.btn_next' : '.btn_prev')).addClass('focus');
			}
		} else {
			if(btn.hasClass('btn_prev') && downup == 'next') {
				btn.removeClass('focus');
				$("li:first-child", this.rootElem).addClass('focus');
			} else if(btn.hasClass('btn_next') && downup == 'prev') {
				btn.removeClass('focus');
				$("li:last-child", this.rootElem).addClass('focus');
			}
		}
	};
	SearchResult.prototype.up = function () {
		CJ.Scene.searchDetail();
	};
	SearchResult.prototype.back = function () {
		CJ.Scene.searchDetail();
	};
	SearchResult.prototype.enter = function () {
		var sIdx;
		var now = $("li.focus", this.rootElem);
		var btn = $(this.rootID + " .btn.focus");
		if (now.length>0) {
			this.viewVod();
		} else {
			this.extend();
			if(btn.hasClass('btn_prev')) {
				sIdx = this.sIdx - 4;
			} else {
				sIdx = this.sIdx + 4;
			}
			if(sIdx >= 0 && sIdx < SearchResult.lists.length) {
				this.render(sIdx);
			}
		}
	};
	SearchResult.prototype.viewVod = function () {
		//컨텐츠 선택
		var now = $("li.focus", this.rootElem);
		var title = now.children('h4').text();
		var eid = now.data('episodeid');
		var pid = now.data('programid');
		var cid = now.data('channelid');
		var likeCnt = now.data('likecount');
		
		var price;
		//과금 체크 및 과금 후 재생 요청 
		function vaildUser () { //과금유저
			//channel, program, episode 데이터 읽어 보기
			CJ.SubList.loadAllList(cid, pid, eid);
			//video 플레이
			VideoPlay(title, likeCnt, pid, eid);
		}
		function invalidUser () {//미과금유저
			CJ.Scene.billing(pid, eid, price, vaildUser);
		}
		// 가격 정보 & 성인 등급 조회
		CJ.plugin.billing.getPrice(pid, eid, function (json) {
			price = {"vodprice" : json.vodprice, "seriesprice" : json.seriesprice, "flatprice" : json.flatprice};
			var grade = json.grade;
			
			CJ.plugin.billing.checkBilling( pid, eid,
								vaildUser,
								invalidUser,
								grade);
		});
	};
	
	function VideoPlay (title, likeCnt, pid, eid) { //과금유저
		$('#vod>h3>span').text(title);
		$('#vod>h3 .num').text(likeCnt);
		CJ.Video.play(pid, eid, CJ.Scene.searchResult);
	}
	
	//LG 키패드가 사라지면 검색 버튼에 자동 포커스 및 LG 키보드에서 input 에 컬러를 자동으로 바꿔줘야 하는데
	//처리가 안되는 것을 강제로 컬러를 지움
	function lgKbHide () {
		 setTimeout(function(){
			$('#searchInput').css('background-color', '');
			$('#search .submit').addClass('focus');
		}, 10);
	}
	
	function lgKbEnter () {
		CJ.Scene["SearchDetail"].enterInputField();
	}
	
	$.extend(CJ.Scene, {
							search: function(){
								CJ.isRightDetailEntry = false;
								$("#wrap").removeClass().addClass('ch');
								$('#global li').removeClass('focus');
								$('#global .search').addClass('focus');
								$("#mask").hide();
								this.setDelegate(this["Search"]);
							},
							searchDetail : function () {
								CJ.isRightDetailEntry = true;
								$("#wrap").removeClass().addClass('ch search');
								$('#global li').removeClass('focus');
								$("#mask").show();
								$('#search .focus').removeClass('focus');
								$('#searchInput').focus();
								
								//LG 키패드를 매직마우스로 없애면 다음번 포커스가 제대로 동작하지만
								//4방향 키로 오른쪽 맨하단 키보드 감추기 버튼을 누른 경우 다음 번부터는 input에 포커스가 들어가도
								//LG 키패드가 나오지 않음 
								//강제로 키패드가 나오도록 호출
								CJ.util.lgKbForceShow($('#searchInput')[0]);
								
								SearchResult.init();
								this.setDelegate(this["SearchDetail"]);
								
								lgKb.enterInputField = lgKbEnter;
							},
							searchResult : function () {
								$("#wrap").removeClass().addClass('ch search');
								$('#search .searchBtn .focus').removeClass('focus');
								if ($('#searchResultList li.focus').length == 0) {
									$('#searchResultList li:first-child').addClass('focus');
								}
								this.setDelegate(this["SearchResult"]);
							}
						});

	$(document).ready(function(){
		CJ.Scene["Search"] = new Search();
		CJ.Scene["SearchDetail"] = new SearchDetail();
		CJ.Scene["SearchResult"] = new SearchResult();
		
		LgKeyBoardHandler.addEventListener('hide', lgKbHide);
	});
})();